<template>
	<el-dialog :visible.sync="dialogVisible" title="编辑商品信息" width="1200px" :close-on-click-modal="false" v-drag2anywhere>
		<div class="title">商品信息</div>
		<el-form :model="formData" label-width="100px" :rules="rules" ref="formData">
				<el-row :gutter="10">
				  <el-col :span="6">
				    <el-form-item label="商品编码:" prop="sn">
				      <el-input v-model="formData.sn" placeholder="京东SKU,政采编码,自采编码"></el-input>
				    </el-form-item>
				  </el-col>
				  <el-col :span="6">
				    <el-form-item label="渠道名称:" prop="platform">
				      <el-select v-model="formData.platform" @change="handlePlatformChange">
				        <el-option v-for="(item,index) in platforms" :label="item.label" :key="item.index" :value="item.label">
				        </el-option>
				      </el-select>
				    </el-form-item>
				  </el-col>
				  <el-col :span="12">
				    <el-form-item label="合作商名称:" prop="supname">
				      <el-select v-model="formData.supname" style="width: 100%;" @change="handleSupChange">
				        <el-option v-for="(item,index) in suppliers" :label="item.name" :key="item.index" :value="item.name">
				        </el-option>
				      </el-select>
				    </el-form-item>
				  </el-col>
				</el-row>
			<el-row :gutter="10">
        <el-col :span="18">
        	<el-form-item label="产品名称:" prop="title">
        		<el-input v-model="formData.title"></el-input>
        	</el-form-item>
        </el-col>
				<el-col :span="6">
					<el-form-item label="客户联系人:" prop="client">
						<el-autocomplete v-model="formData.client" placeholder="客户名" :fetch-suggestions="querySearchAsync"
						  style="width: 100%;"></el-autocomplete>
						</el-select>
					</el-form-item>
				</el-col>

			</el-row>
			<el-row>
			  <el-col :span="12">
			    <el-row>
			      <el-col :span="12">
			        <el-form-item label="品牌:" prop="brand">
			          <el-input v-model="formData.brand" placeholder="请输入品牌"></el-input>
			        </el-form-item>
			      </el-col>
			      <el-col :span="12">
			        <el-form-item label="规格型号:" prop="brand">
			          <el-input v-model="formData.model" placeholder="规格型号"></el-input>
			        </el-form-item>
			      </el-col>
			      <el-col :span="12">
			        <el-form-item label="计量单位:" prop="unit">
			          <el-input v-model="formData.unit" placeholder="计量单位"></el-input>
			        </el-form-item>
			      </el-col>
			      <el-col :span="12">
			        <el-form-item label="单价:" prop="price">
			          <el-input-number v-model="formData.price" :precision="2" style="width: 100%;">
			          </el-input-number>
			        </el-form-item>
			      </el-col>
			    </el-row>
			  </el-col>
			  <el-col :span="12">
			    <el-form-item label="详细参数:">
			      <el-input type="textarea" :rows="3" placeholder="商品详细参数" v-model="formData.params" maxlength="500"
			        show-word-limit></el-input>
			    </el-form-item>
			  </el-col>
			</el-row>
			<el-row>
			<el-col>
				<el-form-item label="参考链接:">
					<el-input v-model="formData.cklink" placeholder="其他商城(例如:京东,天猫,淘宝等) 已存在此商品的参考链接">
					</el-input>
				</el-form-item>
			</el-col>
			<el-col>
				<el-form-item label="上架备注:">
					<el-input v-model="formData.memo" type="textarea" rows="3" placeholder="备注信息">
					</el-input>
				</el-form-item>
			</el-col>

			</el-row>
			<el-row>
			  <el-col :span="12">
			    <div class="title">产品图片</div>
			    <div style="color: rgb(153, 153, 153); font-size: 12px; margin-left: 5px; margin-bottom: 20px;">
			      上传图片至少上传三张!</div>
			    <div style="margin-bottom: 20px;">
			      <el-upload list-type="picture-card" ref="thumbupload" :file-list="thumbuploadConfig.imgList"
			        :action="thumbuploadConfig.action" :headers="thumbuploadConfig.headers" :accept="thumbuploadConfig.accept"
			        :limit="thumbuploadConfig.limit" :on-change="handleThumbChange" :auto-upload="false"
			        :on-remove="handleThumbRemove" :on-exceed="handleThumbLimit" multiple
			        :before-remove="handleThumbBeforRemove" :on-preview="handleThumbPreviewPreview">
			        <i class="el-icon-plus"></i>
			      </el-upload>
			    </div>
			  </el-col>
			  <el-col :span="12">
			    <div class="title">产品资质文件</div>
			    <div style="color: rgb(153, 153, 153); font-size: 12px; margin-left: 5px; margin-bottom: 20px;">
			      请上传产品线所需资质文件，例如：商标注册证、CCC证书、厂家授权、检测报告等</div>

			    <el-upload list-type="picture-card" ref="zzupload" :file-list="zzuploadConfig.imgList"
			      :action="zzuploadConfig.action" :headers="zzuploadConfig.headers" :accept="zzuploadConfig.accept"
			      :limit="zzuploadConfig.limit" :on-change="handleZZChange" :auto-upload="false" :on-remove="handleZZRemove"
			      :on-exceed="handleZZLimit" multiple :before-remove="handleZZBeforRemove"
			      :on-preview="handleZZPreviewPreview">
			      <i class="el-icon-plus"></i>
			    </el-upload>
			  </el-col>
			</el-row>

			<AttachUI v-if="attachVisible" ref="attachUI"></AttachUI>
		</el-form>
		<div slot="footer" class="dialog-footer">
			<el-button @click="dialogVisible = false" size="medium">取 消</el-button>
			<el-button type="primary" size="medium" @click="handleSave">保存</el-button>
		</div>
	</el-dialog>
</template>

<script>
  import AttachUI from '@/components/attachviewer.vue'
	export default {
		components: {
			AttachUI
		},
		data() {
			return {
				index: -1,
				formData: {
					id: '',
					platformid: '-1',
					platform: '',
					brand: '',
					model: '',
					price: 1.0,
					unit: '',
					title: '',
					cover:'',
					num: 1,
					cklink: '',
          params:'',
					supid: '',
					supname: '',
					sn: '',
					supinfo: ''
				},
				suppliers: [],
				platforms: [],
				rules: {
					title: [{
						required: true,
						message: "商品名称不能为空",
						trigger: "blur"
					}],
					platform: [{
						required: true,
						message: "请选择产品渠道",
						trigger: "blur"
					}],
					supname: [{
						required: true,
						message: "请选择申请上架的供应商！",
						trigger: "blur"
					}],
					price: [{
						required: true,
						message: "上架价格不能为空",
						trigger: "blur"
					}],
					unit: [{
						required: true,
						message: "计量单位不能为空",
						trigger: "blur"
					}]
				},
				//文件上传相关变量
				thumbuploadConfig: { //产品图片上传
					//文件上传相关参数
					accept: '.jpg,.jpeg,.png',
					limit: 6,
					headers: {
						token: localStorage.getItem('token') != null ? localStorage.getItem('token') : ''
					},
					imgList: [],
					fileList: [],
					removeids: [], //要删除的id
					action: ""
				},
				//文件上传相关变量
				zzuploadConfig: { //产品图片上传
					//文件上传相关参数
					accept: '.pdf,.jpg,.jpeg,.png',
					limit: 10,
					headers: {
						token: localStorage.getItem('token') != null ? localStorage.getItem('token') : ''
					},
					imgList: [],
					fileList: [],
					removeids: [], //要删除的id
					action: ""
				},
				dialogVisible: true,
				attachVisible: false,
				snexist:false
			}
		},
		mounted() {
			this.loadPlatforms();
			this.loadSuppliers();
		},
		methods: {
      querySearchAsync(str, cb) {
        this.axios.post("api/admin/clientuser/filter", {
          username: str
        }).then(res => {
          if (res.data.code) {
            cb(res.data.data);
          }
        })
      },
			initData(index, data) {
				this.index = index;
				this.formData = JSON.parse(JSON.stringify(data));
				this.thumbuploadConfig.imgList = data.thumbs;
				this.zzuploadConfig.imgList = data.zizhi;
			},
			loadPlatforms: function() {
				this.axios.get("api/admin/platform/list").then((res) => {
					if (res.status == 200 && res.data.code == 0) {
						this.platforms = res.data.platforms;
					}
				})
			},
			loadSuppliers: function() {
				this.axios.post("api/admin/supplier/list").then((res) => {
					if (res.status == 200 && res.data.code == 0) {
						this.suppliers = res.data.list;
					}
				});
			},
			handleSupChange: function(sup) {
				var option = this.suppliers.filter(function(cur, index, a) {
					if (cur.name == sup) {
						return cur;
					}
				})[0];
				this.formData.supid = option.id;
				this.formData.supname = option.name;
			},
			handlePlatformChange: function(platform) {
				var option = this.platforms.filter(function(cur, index, a) {
					if (cur.label == platform) {
						return cur;
					}
				})[0];
				this.formData.platformid = option.id;
				this.formData.platform = option.label;
			},
			handlechecksn:function(){
				this.axios.get("api/admin/arrival/jdarrival/checksn",{params:{sn:this.formData.sn,id:this.formData.id}}).then(res=>{
					if(res.status==200 && res.data.code==0){
						this.snexist=true;
						this.$alert("此商品编码已经存在!",{type:'error'});
					}else{
						this.snexist=false;
					}
				});
			},
			handleSave: function() {
				if(this.snexist){
					this.$alert("请仔细核对商品编码，此商品编码已经存在!",{type:'error'});
					return;
				}
				if (this.$refs.formData.validate((ok) => {
						if (ok) {

							let fd = new FormData();
							//添加要删除的附件id
							fd.append("id", this.formData.id);
							fd.append("sn",this.formData.sn);
							fd.append("rmthumbids", this.thumbuploadConfig.removeids.join(","));
							fd.append("rmzzids", this.zzuploadConfig.removeids.join(","));
							fd.append("platformid",this.formData.platformid),
							fd.append("platform",this.formData.platform),
							fd.append("brand", this.formData.brand);
							fd.append("model", this.formData.model);
              fd.append("params",this.formData.params);
							fd.append("title",this.formData.title);
							fd.append("client",this.formData.client);
              fd.append("unit", this.formData.unit);
							fd.append("supid",this.formData.supid);
							fd.append("supname",this.formData.supname);
							fd.append("status",this.formData.status);
							fd.append("num", this.formData.num);
              fd.append("cklink",this.formData.cklink);
							fd.append("price", this.formData.price);
							fd.append("cklink", this.formData.cklink);
							fd.append("memo", this.formData.memo);
							let fid = 0;
							this.thumbuploadConfig.fileList.forEach(file => {
								if (file.raw) {
									fd.append("thumb_" + fid, file.raw);
									fid++;
								}
							});

							fid=0;
							this.zzuploadConfig.fileList.forEach(file=>{
								if(file.raw){
									fd.append("zizhi_"+fid,file.raw);
								}
							});


							this.$axiosUploader.post("api/admin/product/update", fd).then(res => {
								if (res.status == 200 && res.data.code == 0) {
									this.thumbuploadConfig.imgList = res.data.thumbs;
									this.zzuploadConfig.imgList=res.data.zizhi;
									this.$emit("closeHandler",this.index,this.formData,this.thumbuploadConfig.imgList,this.zzuploadConfig.imgList);
									this.$message({
										message: "保存成功!",
										showClose: true,
										type: 'success',
										duration: 1500
									});
                  this.dialogVisible=false;
									this.thumbuploadConfig.fileList=[];
									this.thumbuploadConfig.removeids=[];
									this.zzuploadConfig.fileList=[];
									this.zzuploadConfig.removeids=[];
									this.$refs.thumbupload.clearFiles();
									this.$refs.zzupload.clearFiles();
							}
								//this.$emit("closeHandler", this.index,fd);
							});
						}
					}));
 			},
			//产品图片上传处理
			handleThumbChange: function(file, list) {
				//判断文件格式和数量
				var ext = file.name.substr(file.name.lastIndexOf('.') + 1).toLowerCase();
				var extarr = ['jpg', 'jpeg', 'png'];
				var sizeok = file.size / 1024 / 1024 < 2;
				if (extarr.lastIndexOf(ext) == -1) {
					this.$message.error("上传文件格式必须为" + extarr.join(","));
					//删除刚上传的文件
					this.thumbuploadConfig.fileList.splice(this.thumbuploadConfig.fileList.length - 1, 1);
					return;
				}
				if (!sizeok) {
					this.$message.error("上传文件大小最大不超过1M");
					this.thumbuploadConfig.fileList.splice(this.thumbuploadConfig.fileList.length - 1, 1);
					return;
				}

				this.thumbuploadConfig.fileList = list;
			},
			handleThumbBeforRemove: function(file, FileList) {
				return this.$confirm("此操作将会删除当前图片，是否继续?", "提示", {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				})
			},
			handleThumbRemove: function(file) {
				if (file.id) { //如果存储 id即为已经上传好的图片
					this.thumbuploadConfig.removeids.push(file.id);
				}
			},
			handleThumbLimit: function() {
				this.$message.warning("最多可上传" + this.thumbuploadConfig.limit + "个文件");

			},
			handleThumbPreviewPreview: function(file) {
        this.attachVisible=true;
       this.$nextTick(() => {
         this.$refs.attachUI.dialogVisible = true;
         this.$refs.attachUI.initData(JSON.parse(JSON.stringify(this.thumbuploadConfig.imgList)));
       })


			},

			/***资质附件**/
			handleZZChange: function(file, list) {
				//判断文件格式和数量
				var ext = file.name.substr(file.name.lastIndexOf('.') + 1).toLowerCase();
				var extarr = ['jpg', 'jpeg', 'png', "doc", "docx", "xls", "xlsx", "pdf"];
				var sizeok = file.size / 1024 / 1024 < 2;
				if (extarr.lastIndexOf(ext) == -1) {
					this.$message.error("上传文件格式必须为" + extarr.join(","));
					//删除刚上传的文件
					this.zzuploadConfig.fileList.splice(this.zzuploadConfig.fileList.length - 1, 1);
					return;
				}
				if (!sizeok) {
					this.$message.error("上传文件大小最大不超过2M");
					this.zzuploadConfig.fileList.splice(this.zzuploadConfig.fileList.length - 1, 1);
					return;
				}
				this.zzuploadConfig.fileList = list;
			},
			handleZZBeforRemove: function(file, FileList) {
				return this.$confirm("此操作将会删除当前图片，是否继续?", "提示", {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				})
			},
			handleZZRemove: function(file) {
				if (file.id) { //如果存储 id即为已经上传好的图片
					this.zzuploadConfig.removeids.push(file.id);
				}
			},
			handleZZLimit: function() {
				this.$message.warning("最多可上传" + this.zzuploadConfig.limit + "个文件");

			},
			handleZZPreviewPreview: function(file) {
        this.attachVisible=true;
        this.$nextTick(() => {
          this.$refs.attachUI.dialogVisible = true;
          this.$refs.attachUI.initData(JSON.parse(JSON.stringify(this.zzuploadConfig.imgList)));
        })
			}
		}
	}
</script>

<style>
	.title {
		position: relative;
		padding-left: 10px;
		margin-bottom: 15px;
		font-size: 14px;
		color: #333;
		font-weight: 700;
	}

	.title:before {
		content: "";
		position: absolute;
		top: 4px;
		left: 0;
		width: 5px;
		height: 65%;
		background-color: #249af3;
	}

	// 上传图片框样式
	.el-upload-list el-upload-list--picture-card {
		height: 96px !important;
		width: 96px !important;
		line-height: 96px !important;
	}

	.el-upload--picture-card {
		height: 96px !important;
		width: 96px !important;
		line-height: 96px !important;
	}

	.el-upload-list__item {
		height: 96px !important;
		width: 96px !important;
		line-height: 96px !important;
	}

	.el-upload-list__item-status-label i {
		position: absolute;
		width: 12x;
		right: 12px;
		top: 0px;
	}

	.el-upload--picture-card {
		height: 96px !important;
		width: 96px !important;
		line-height: 96px !important;
	}

	.el-upload-list__item {
		height: 96px !important;
		width: 96px !important;
		line-height: 96px !important;
		transition: none !important;
	}

	.el-upload-list__item-status-label i {
		position: absolute;
		width: 12x;
		right: 12px;
		top: 0px;
	}
</style>
